package com.catering.project.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.catering.domain.Order;
import com.catering.domain.OrderList;
import com.catering.domain.OrderOrderlist;
import com.catering.domain.Table;
import com.catering.mapper.OrderListMapper;
import com.catering.mapper.OrderMapper;
import com.catering.mapper.OrderOrderlistMapper;
import com.catering.project.domain.OrderData;
import com.catering.project.service.impl.CartServiceImpl;
import com.catering.service.impl.TableServiceImpl;
import com.github.pagehelper.PageInfo;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.catering.common.annotation.Log;
import com.catering.common.core.controller.BaseController;
import com.catering.common.core.domain.AjaxResult;
import com.catering.common.enums.BusinessType;
import com.catering.project.domain.Cart;
import com.catering.project.service.ICartService;
import com.catering.common.utils.poi.ExcelUtil;

/**
 * 购物车Controller
 *
 * @author ruoyi
 * @date 2024-10-18
 */
@RestController
@RequestMapping("/project/cart")
public class CartController extends BaseController
{
    @Autowired
    private ICartService cartService;
    @Autowired
    private CartServiceImpl cartServiceimpl;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderListMapper orderListMapper;

    //copy
    @Autowired
    private OrderOrderlistMapper orderOrderlistMapper;
    @Autowired
    private TableServiceImpl tableService;
    /**
     * 查询购物车列表
     */

    @PreAuthorize("@ss.hasPermi('project:cart:list')")
    @GetMapping("/list")
    public PageInfo<Map<String, Object>> list1(@RequestParam(required = false) Integer tableId) {

        if (tableId == null) {
            List<Map<String, Object>> list = cartService.selectCartList0(tableId);
            System.out.println(list);
            return new PageInfo<>(list);
        } else {
            List<Map<String, Object>> list = cartService.selectCartList0(null);
            System.out.println(list);
            return new PageInfo<>(list);
        }
    }



    /**
     * 导出购物车列表
     */
    @PreAuthorize("@ss.hasPermi('project:cart:export')")
    @Log(title = "购物车", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Cart cart)
    {
        List<Cart> list = cartService.selectCartList(cart);
        ExcelUtil<Cart> util = new ExcelUtil<Cart>(Cart.class);
        util.exportExcel(response, list, "购物车数据");
    }

    /**
     * 获取购物车详细信息
     */
    @PreAuthorize("@ss.hasPermi('project:cart:query')")
    @GetMapping(value = "/{cartId}")
    public AjaxResult getInfo(@PathVariable("cartId") Long cartId)
    {
        return success(cartService.selectCartByCartId(cartId));
    }

    /**
     * 新增购物车
     */
//    @PreAuthorize("@ss.hasPermi('project:cart:add')")
//    @Log(title = "购物车", businessType = BusinessType.INSERT)
//    @PostMapping
//    public AjaxResult add(@RequestBody Cart cart)
//    {
//        return toAjax(cartService.insertCart(cart));
//    }


    @PreAuthorize("@ss.hasPermi('project:cart:add')")
    @Log(title = "购物车", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Cart cart)
    {
        List<Cart> cartList=cartService.selectAllByTableIdCarts(cart.getTableId());
        for (Cart c:cartList
        ) {
            if (c.getDishId()==cart.getDishId()){
                cart.setQuantity(cart.getQuantity()+1);
                return toAjax(cartService.updateCart(cart)) ;
            }
        }
        return toAjax(cartService.insertCart(cart));
    }
    /**
     * 修改购物车
     */
    @PreAuthorize("@ss.hasPermi('project:cart:edit')")
    @Log(title = "购物车", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Cart cart)
    {
        return toAjax(cartService.updateCart(cart));
    }

    /**
     * 删除购物车
     */
    @PreAuthorize("@ss.hasPermi('project:cart:remove')")
    @Log(title = "购物车", businessType = BusinessType.DELETE)
    @DeleteMapping("/{cartIds}")
    public AjaxResult remove(@PathVariable Long[] cartIds)
    {
        return toAjax(cartService.deleteCartByCartIds(cartIds));
    }

//    根据桌号将添加菜品集合到购物车

//    @PreAuthorize("@ss.hasPermi('project:cart:add')")
//    @Log(title = "购物车", businessType = BusinessType.INSERT)
//    @PostMapping("/addDishList")
//    public AjaxResult addDishList(@RequestBody Map<String, Object> map) {
//        System.out.println(map);
//        return AjaxResult.success(cartService.addDishList(map));
//    }

    @PreAuthorize("@ss.hasPermi('project:cart:add')")
    @Log(title = "购物车", businessType = BusinessType.INSERT)
    @PostMapping("/addDishList")
    public AjaxResult addDishList(@RequestBody Cart cart) {
        List<Cart> cartList=selectAllByTableIdCarts(Math.toIntExact(cart.getTableId()));

        for (Cart c:cartList
        ) {
            if (c.getDishId()==cart.getDishId()){
                cart.setQuantity(c.getQuantity()+1);
                System.out.println(cart.getQuantity());
                return toAjax(cartService.updateCartByDidAndTid(cart));
            }
        }
        return toAjax(cartService.insertCart(cart));
    }
    @PreAuthorize("@ss.hasPermi('project:cart:remove')")
    @Log(title = "���ﳵ", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleteByTableId/{tableId}")
    public AjaxResult deleteCartByTableId(@PathVariable Long tableId) {
        boolean result = cartService.deleteCartByTableId(tableId);
        if (result) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error("ɾ��ʧ��");
        }
    }

    //    根据桌id查询购物车
    @PreAuthorize("@ss.hasPermi('project:cart:list')")
    @GetMapping("/listByTableId")
    public List<Cart> selectAllByTableIdCarts(Integer tableId){
        return cartService.selectAllByTableIdCarts((long) tableId);
    }

//添加订单,将cart传到order,并清空购物车


    @PostMapping("/settleAccounts")
    public boolean insertOrder(@RequestBody OrderData orderData) {
        int tableId = orderData.getTableId();
        List<Long> dishIds = orderData.getDishIds();
        List<Integer> dishNums = orderData.getDishNums();
        Integer userId = orderData.getUserId();
        Integer totalPrice = orderData.getTotalPrice();
        System.out.println("orderData"+orderData);

        OrderList orderList = new OrderList();
        orderList.setTotalprice(Double.valueOf(totalPrice));
        orderList.setCreatetime(new Date());

        orderListMapper.insertSelective(orderList);


        boolean allInsertsSuccessful = true;
        for (int i = 0; i < dishIds.size(); i++) {
            Integer dishId = Math.toIntExact(dishIds.get(i));
            Integer dishNum = dishNums.get(i);
            try {
                // 这里假设你有一个 OrderMapper 和对应的 SQL 语句来插入订单数据
                // 以下是一个示例，你需要根据实际情况进行调整
                Order order = new Order();
                order.setUserId(userId);
                order.setTableId(tableId);
                order.setDishId(dishId);
                order.setDishNum(dishNum);
                order.setStatus(1);
                System.out.println(order+"orderoredr==================================");
                System.out.println("插入订单数据：userId=" + userId + ", tableId=" + tableId + ", dishId=" + dishId + ", dishNum=" + dishNum);
                int rowsAffected = orderMapper.insertSelective(order);
                if (rowsAffected <= 0) {
                    allInsertsSuccessful = false;
                    break;
                }

            } catch (Exception e) {
                allInsertsSuccessful = false;
                break;
            }
        }

        //copy
        List<Order> orders = orderMapper.getAddOrder(dishIds.size());
        OrderList order_list = orderListMapper.getNewOrderList();
        int orderList_id = order_list.getId();
        for (Order o : orders) {
            OrderOrderlist orderOrderlist = new OrderOrderlist();
            orderOrderlist.setOrderlistId(orderList_id);
            orderOrderlist.setOrderId(o.getId());
            System.out.println(orderOrderlist);
            orderOrderlistMapper.insertSelective(orderOrderlist);
        }
        cartServiceimpl.deleteCartByTableId((long)orderData.getTableId());
        tableService.updateStausIdToOneById((long)tableId);
        return allInsertsSuccessful;
    }

}
